#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <muduo/base/CountDownLatch.h>
#include <iostream>
#include <string>

class Dictclient
{
public:
    Dictclient(const std::string &ip, int port)
        : _cloop(_loopthread.startLoop()), _cdown(1), _client(_cloop, muduo::net::InetAddress(ip, port), "Dictclient")
    {
        _client.setConnectionCallback(std::bind(&Dictclient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&Dictclient::onMessage, this,
                                             std::placeholders::_1,
                                             std::placeholders::_2,
                                             std::placeholders::_3));
        _client.connect();
        _cdown.wait();
    }
    bool Send(std::string &msg)
    {
        if (_conn->connected() == false)
        {
            std::cout << "连接已经断开,发送信息失败" << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            std::cout << "连接建立成功" << std::endl;
            _cdown.countDown();
            _conn = conn;
        }
        else
        {
            std::cout << "连接断开" << std::endl;
            _conn.reset();
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::string msg = buf->retrieveAllAsString();
        std::cout << msg << std::endl;
    }

private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _cdown;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop *_cloop;
    muduo::net::TcpClient _client;
};

int main()
{
    Dictclient _client("127.0.0.1", 8080);
    while (1)
    {
        std::string msg;
        std::cin >> msg;
        _client.Send(msg);
    }

    return 0;
}